package org.budo.elasticsearch.jdbc.driver;

import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import org.budo.jdbc.driver.AbstractBudoJdbcConnection;
import org.budo.jdbc.driver.statement.JdbcStatement;
import org.elasticsearch.client.transport.TransportClient;

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

/**
 * @author lmw
 */
@Accessors(chain = true)
@Getter
@Setter
public class BudoElasticsearchJdbcConnection extends AbstractBudoJdbcConnection {
    private TransportClient transportClient;

    @SuppressWarnings("resource")
    @Override
    public PreparedStatement prepareStatement(String sql) throws SQLException {
        JdbcStatement jdbcStatement = this.statementParser().parse(sql);

        return (PreparedStatement) new BudoElasticsearchJdbcPreparedStatement() //
                .setJdbcStatement(jdbcStatement) //
                .setConnection(this);
    }

    @SuppressWarnings("resource")
    @Override
    public Statement createStatement() throws SQLException {
        return new BudoElasticsearchJdbcStatement() //
                .setConnection(this);
    }

    @Override
    public void close() throws SQLException {
        this.getTransportClient().close();

        super.close();
    }

    @Override
    public DatabaseMetaData getMetaData() throws SQLException {
        return new BudoElasticsearchJdbcDatabaseMetaData() //
                .connection(this);
    }
}
